from fastapi import APIRouter, Depends, Path, Query
from apps.model.crud import (
   create_project, query_project_by_id,
   update_project, delete_project,
   query_all_project
)
from apps.model.schames import ProjectIn, ProjectOut, ProjectUpdateIn
from fastapi_jwt_auth import AuthJWT
from sqlalchemy.orm import Session
from apps.utils.depends import get_db
from typing import List, Optional

router = APIRouter()


@router.post('/project', response_model=ProjectOut)
def create_project_view(
        body: ProjectIn,
        Authorize: AuthJWT = Depends(),
        db: Session = Depends(get_db)
 ):
    print(f"用户传过来的数据: {body.dict()}")
    # 登录验证
    Authorize.jwt_required()
    # 得到登录用户token解析的数据
    claims = Authorize.get_raw_jwt()
    print(claims)
    user_id = claims.get('user_id')
    # 创建项目
    obj = create_project(db, body, user_id=user_id)
    return obj


@router.get('/project/{_id}', response_model=ProjectOut)
def get_project_by_id(_id: int = Path(..., title='项目id'),
                      db: Session = Depends(get_db),
                      Authorize: AuthJWT = Depends(),
                      ):
    # 登录验证
    Authorize.jwt_required()
    # 查询 项目id
    print(f'项目id: {_id}')
    # 暂时没加身份认证
    obj = query_project_by_id(db, _id)
    return obj


@router.put('/project/{_id}', response_model=ProjectOut)
def update_project_by_id(body: ProjectUpdateIn,
                         _id: int = Path(..., title='项目id'),
                         db: Session = Depends(get_db),
                         Authorize: AuthJWT = Depends(),
                         ):
   # 登录验证
   Authorize.jwt_required()
   # 用户没有传的参数，pydantic 校验数据的时候，去掉  exclude_unset=True
   print(f"用户传入的参数: {body.dict(exclude_unset=True)}")
   project = update_project(db, _id, body)
   return project


@router.delete('/project/{_id}')
def delete_project_by_id(_id: int = Path(..., title='项目id'),
                         db: Session = Depends(get_db),
                         Authorize: AuthJWT = Depends()
                         ):
    Authorize.jwt_required()
    # 删除
    delete_project(db, _id)
    return {"message": "delete success!"}


@router.get('/project', response_model=List[ProjectOut])
def get_all_project(
        page: int = Query(1, title='页数', ge=1),
        size: int = Query(10, ge=1, le=20, title='数量'),
        project_name: Optional[str] = Query('', title='项目名称'),
        db: Session = Depends(get_db),
        Authorize: AuthJWT = Depends()
):
    # 查询全部
    Authorize.jwt_required()
    print(f"项目名称：{project_name}")
    res = query_all_project(db, page, size, project_name)
    return res


